package com.erp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.erp.Utils.ResponseModel;
import com.erp.entity.MyUser;
import com.erp.entityVo.MyUserVo;
import com.erp.security.dto.JwtUserDto;
import com.erp.service.MyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  CJ 
 * @since 2021-10-09
 */
@Controller
@RequestMapping("/api/user")
@Api(tags = "系统：用户管理")
public class MyUserController {
    @Resource
    private MyUserService myUserService;

    @GetMapping("/index")
    @ApiOperation("进入用户页面")
    @PreAuthorize("hasAnyAuthority('user:list')")
    public String index(){
        return "system/user/user";
    }
    @ResponseBody
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    @PreAuthorize("hasAnyAuthority('user:list')")
    public Map<String,Object> userList(@RequestParam(value = "user_name",required = false) String user_name,
                                       @RequestParam(value = "nick_name",required = false) String nick_name,
                                       @RequestParam(value = "page") int page,
                                       @RequestParam(value = "limit") int limit){
        return myUserService.userList(user_name,nick_name,page,limit);
    }

    @GetMapping("/add")
    @ApiOperation("新增用户")
    @PreAuthorize("hasAnyAuthority('user:add')")
    public String add(){
        return "system/user/user-add";
    }

    @PostMapping("/save")
    @ApiOperation("保存用户")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('user:add')")
    public ResponseModel save(@RequestBody MyUserVo myUserVo){
        if (StrUtil.isEmpty(myUserVo.getUserName()) || StrUtil.isEmpty(myUserVo.getPassword())){
            return ResponseModel.fail("用户名和密码参数缺少");
        }
        if (myUserService.checkUserExists(myUserVo.getUserName()) != null){
            return ResponseModel.fail("用户已存在,无法创建");
        }
        if (StrUtil.isNotEmpty(myUserVo.getPassword())){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            myUserVo.setPassword(bCryptPasswordEncoder.encode(myUserVo.getPassword()));
        }
        return myUserService.saveUser(myUserVo);
    }
    @GetMapping("/edit")
    @ApiOperation("修改用户页面")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ModelAndView edit(@RequestParam String userId){
//        String md5Password = DigestUtils.md5DigestAsHex("222".getBytes());
        return myUserService.editView(userId);
    }
    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation("修改用户数据")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ResponseModel edit(@RequestBody JSONObject user){
        return myUserService.editUser(user);
    }

    @DeleteMapping("/delete/{user_id}")
    @ResponseBody
    @ApiOperation("删除数据")
    @PreAuthorize("hasAnyAuthority('user:del')")
    public ResponseModel delete(@PathVariable("user_id") String user_id){
        return myUserService.deleteUser(user_id);
    }

    @PutMapping("/changeStatus")
    @ResponseBody
    @ApiOperation("修改用户状态")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ResponseModel changeStatus(@RequestBody JSONObject data){

        return myUserService.changeStatus(data);
    }

    // 修改密码
    @ApiOperation("修改密码视图")
    @RequestMapping(value = "/changePwd",method = RequestMethod.GET)
    public ModelAndView changePwd(HttpServletRequest request){
//        Map<String,Object> map = getLoginUser.getSession(request);
        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("userName",map.get("userName"));
//        modelAndView.addObject("userId",map.get("userId"));
        //        获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        modelAndView.addObject("userName",userName);
        Integer userId = jwtUserDto.getMyUser().getUserId();
        modelAndView.addObject("userId",userId);
        modelAndView.setViewName("system/user/changePwd");
        return modelAndView;
    }

    @ResponseBody
    @ApiOperation("修改密码")
    @RequestMapping(value = "/change",method = RequestMethod.POST)
    public ResponseModel changePwd(@RequestBody Map<String,String> data){
        String userId = data.get("userId");
        String userPwd = data.get("usedPwd");
        String newPwd = data.get("newPwd");
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(userPwd) ||
                StrUtil.isEmpty(newPwd)){
            return ResponseModel.fail("缺少参数");
        }
        MyUser myUser = myUserService.getUser(userId);
        // 效验旧密码
        if (!new BCryptPasswordEncoder().matches(userPwd,myUser.getPassword())){
            return ResponseModel.fail("抱歉，你输入的旧密码错误,无法执行修改操作");
        }
//      // 新密码写入到数据库
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String passHash = bCryptPasswordEncoder.encode(newPwd);
        MyUser myUser1 = new MyUser();
        myUser1.setPassword(passHash);
        myUser1.setUserId(myUser.getUserId());
        int updateStatus = myUserService.changePwd(myUser1);
        if (updateStatus > 0){
            return ResponseModel.success("修改密码成功");
        }else{
            return ResponseModel.fail("修改密码失败");
        }
    }
}
